//
//  MYGHospitalViewController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/5/16.
//

import UIKit
import MJRefresh
import QMUIKit

class MYGHospitalViewController: MYGBaseController {
    
    var callHospitailName:((_ name:String)->Void)?
    
    private var page = 1
    private var contents: [MYGHospitalModel] = []
    private var searchStr: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }
    func configUI(){
        view.backgroundColor = .white
        self.navigationController?.navigationBar.isHidden = true
        
        view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        
        view.addSubview(searchContentView)
        searchContentView.snp.makeConstraints { make in
            make.left.equalTo(backButton.snp.right).offset(14)
            make.centerY.equalTo(backButton)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(28)
        }
        
        searchContentView.addSubview(searchTextFiled)
        searchTextFiled.snp.makeConstraints { make  in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalTo(backButton)
            make.height.equalTo(SCALEWIDTH(30))
            make.right.equalToSuperview().offset(-SCALEWIDTH(20))
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(searchContentView.snp.bottom)
        }
        
        tableView.mj_header?.beginRefreshing()
    }
    
    private lazy var searchContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(243, 243, 243)
        view.layerCornerRadius = 14
//        view.clipsToBounds = true
        
        view.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.07).cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 1)
        view.layer.shadowOpacity = 1
        view.layer.shadowRadius = 7
        
        return view
    }()
    private lazy var backButton:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "comonback"), for: .normal)
        btn.imageView?.tintColor = .rgba(51, 51, 51, 1)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    private lazy var searchTextFiled: QMUITextField = {
        let tf = QMUITextField()
        tf.font = .regular(13)
        tf.textInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        tf.clearButtonMode = .whileEditing
        tf.returnKeyType = .search
        let placeholderAtt = NSAttributedString(string: "搜索", attributes: [.foregroundColor: UIColor.rgba(124, 124, 124)]);
        tf.attributedPlaceholder = placeholderAtt;
        let leftImageView = UIImageView(image: UIImage(named: "Community/search"))
        leftImageView.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        tf.leftView = leftImageView
        tf.leftViewMode = .always
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEnd)
        tf.addTarget(self, action: #selector(textFiledEdtingEnded), for: .editingDidEndOnExit)
        //tf.contentEdgeInsets = .init(top: 0, left: 15, bottom: 0, right: 0)
        tf.layer.cornerRadius = 15
        tf.layer.shadowRadius = 7
        tf.layer.shadowOffset = CGSize(width: 0, height: 1)
        tf.layer.shadowOpacity = 0.07
        tf.layer.shadowColor = UIColor.black.cgColor
        return tf
    }()
    
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .white
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.register(cellWithClass: MYGHospitailCell.self)
        tableV.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getList()
        })
        
        tableV.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getList()
        })
        return tableV
    }()
    
    override var hideNavigationController: Bool {
        true
    }
}

extension MYGHospitalViewController:UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        53
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGHospitailCell.self, for: indexPath)
        cell.nameLabel.text = contents[indexPath.row].hosp_name
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let name = contents[indexPath.row].hosp_name
        callHospitailName?(name)
        navigationController?.popViewController()
    }
}

extension MYGHospitalViewController {
    
    //获取医院列表
    func getList(){
        MYGLoading.show()
        MMYGNetwork<MYGResumeApi, MYGPageModel<MYGHospitalModel>>.request(target: .hospitals(kwd: searchStr, hosp_type: "", hosp_level: "", address: "",page:page)) { item in
            MYGLoading.hide()
            guard let item = item else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.contents = item.list
            } else {
                self.contents.append(contentsOf: item.list)
            }
            
            if item.page.total <= self.contents.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.tableView.reloadData()
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }

    }
    
    @objc
    private func clickButton(_ btn: UIButton) {
        self.navigationController?.popViewController()
    }
    
    @objc func textFiledEdtingEnded() {
        self.searchStr = searchTextFiled.text!
        getList()
    }
}


class MYGHospitailCell :UITableViewCell {
    
    
    // MARK: - init
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configUI(){
        contentView.backgroundColor = .white
        
        contentView.addSubview(nameLabel)
        contentView.addSubview(line)
        
        nameLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        line.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
    }
    
     lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        label.textColor = .rgba(51, 51, 51, 1)
        label.text = "医院"
         label.textAlignment = .center
        return label
    }()
    
    private lazy var line: UIView = {
        let line = UIView()
        line.backgroundColor = .rgba(242, 242, 242, 1)
        return line
    }()
    
}
